/**
 * 我的工作台
 */

import styled from "@emotion/styled";
import { Avatar, Button, Card, Input, Modal, Space, Table, Tooltip } from "antd";
import { useRecoilState } from "recoil";
import { userState } from "../../../stores/user";
import SvgIcon from "../../../components/svgIcon";
import { IBeef, useGetUserBaseStatitic } from "../../../service/beef/beef-service";
import { TableContainer } from "../../../csscomponents/base";
import { ErrorBox } from "../../../components/error-box";
import { useCallback, useEffect, useRef, useState } from "react";
import { useGetBeefType } from "../../../service/beef-type-service";
import BeefForm from "../beef/beef-form";
import BeefRisk from "../beef/beef-risk";
import { IFormRef } from "../../../types";
import BeefSloveStepForm from "../beef/beef-solve-setp-form";
import { useAddBeefSolveStep ,useOverBeefSolveStep ,usePushBeefSolveStep ,useSignBeefSolveStep ,useRollbackBeefSolveStep ,useConfirmEndBeefSolveStep,usePushAppointBeefSolveStep} from "../../../service/beef/beef-solve-service";


import AssignForm from "./assign-form";
import ProcessForm from "./process-form";
import TextArea from "antd/es/input/TextArea";
import { todoState } from "../../../stores/todo";
import { useNavigate } from "react-router";
import { naviState } from "../../../stores/navi";
const WorkPlacePage = () => {
  const [sys] = useRecoilState(userState);
  const [, setTodoCount] = useRecoilState(todoState);
  const navigate = useNavigate();

  const [open, setOpen] = useState<boolean>(false);
  const [openRisk, setOpenRisk] = useState<boolean>(false)
  const [openBeefSolveStep, setOpenBeefSolveStep] = useState<boolean>(false)
  const [assignOpen, setAssionOpen] = useState<boolean>(false)
  const [processOpen, setProcessOpen] = useState<boolean>(false)
  const FormRef = useRef<IFormRef>();
  //需要修改的风险评估的矛盾纠纷ID
  const [beefId, setBeefId] = useState<string>()
  const [beefIdAssign, setBeefIdAssign] = useState<string>()
  const [beefIdSlove, setBeefIdSlove] = useState<string>()
  const [beefIdProcess, setBeefIdProcess] = useState<string>()
  //需要修改的矛盾纠纷
  const [update, setUpdate] = useState<IBeef>();
  const [isEdit ,setIsedit] = useState<number>(0)
  /**
     * 关闭风险评估
     */
  const closeBeefRiskFn = useCallback((open: boolean) => {
    setOpenRisk(open)
    setBeefId(undefined)
  }, [])
  //关闭流程
  const closeBeefSolveStepHandler = useCallback((open: boolean) => {
    setOpenBeefSolveStep(false)
    setBeefId(undefined)
  }, [])

  //关闭指派人员
  const closeAssignHandler = useCallback((open: boolean) => {
    setAssionOpen(false)
    setBeefIdAssign(undefined)
  }, [])
  const closeProcessHandler = useCallback(() => {
    setProcessOpen(false)
    setBeefIdProcess(undefined)
  }, [])
  /**
  * 打开基本信息form
  */
  const openFn = useCallback((open: boolean) => {
    setOpen(open)
  }, [])
  // 保存与修改

  const [navi, setNavi] = useRecoilState(naviState);
  /**
   * !获取工作台统计Hook
   */
  const { isLoading, isError, data: dataSource, error, refetch } = useGetUserBaseStatitic();


  useEffect(() => {
    refetch();
  }, [sys])

  useEffect(() => {
    setTodoCount({ count: dataSource?.todo || 0 })
  }, [dataSource])

  /**
   * !添加矛盾纠纷步骤;
   */
  const { mutateAsync: addMutation } = useAddBeefSolveStep();
  //结束矛盾纠纷
  const {mutateAsync:overMutation} = useOverBeefSolveStep()
  //推送到综治中心
  const {mutateAsync:pushMutation} = usePushBeefSolveStep()
  // 签收
  const {mutateAsync:signMutation} = useSignBeefSolveStep()
  //退回重新调解
  const {mutateAsync:rollbackMutation} = useRollbackBeefSolveStep()
  //电话回访 彻底结束流程
  const {mutateAsync:confirmEndMutation} = useConfirmEndBeefSolveStep()

  const { data: dataSourceBeefType } = useGetBeefType({
    beefTypeName: "",
    page: 1,
    limit: -1
  });
  const openRiskDrawHandler = (beefId: string) => {
    setBeefId(beefId)
    setOpenRisk(true)
  }

  const [msg, setMsg] = useState<string>();
  const handleInputValue: React.ChangeEventHandler<HTMLTextAreaElement> = (e) => {
    setMsg(e.target.value);
  };


  /**
   * 签收任务
   */
  const signalBeefHandler = (beefId: string) => {

    Modal.confirm({
      title: '⚠️警告 ',
      content: '你确认签收该任务吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await signMutation({ beefId});
        refetch();
      },
    });
  }
  /**
   * 送到综治中心
   */
  const sendToZSZXHandler = (beefId: string) => {

    Modal.confirm({
      title: '⚠️警告 你确认该任务推送到综治中心吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await pushMutation({ beefId });
        refetch();
      },
    });
  }


  /**
 * 结束任务
 */
  const overBeefHandler = (beefId: string) => {
    setMsg("");
    Modal.confirm({
      title: '⚠️警告 你确认结束该任务吗',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await overMutation({ beefId });
        refetch();
      },
    });
  }

  /**
 * 电话回访
 */
  const callBackHandler = (beefId: string) => {
    setMsg("");
    Modal.confirm({
      title: '⚠️警告 确定已经电话回访了吗',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await confirmEndMutation({ beefId });
        refetch();
      },
    });
  }

  /**
 * 退回重新评估
 */
  const backTORiskHandler = (beefId: string) => {
    Modal.confirm({
      title: '⚠️警告 退回重新评估',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await rollbackMutation({ beefId });
        refetch();
      },
    });
  }
    /**
 * 综治中心指派给社区书记
 */
    // const pushAppointBeefHandler = (beefId: string) => {
    //   setMsg("");
    //   Modal.confirm({
    //     title: '⚠️警告 你确认结束该任务吗',
    //     content: <TextArea placeholder="描述" onChange={handleInputValue} />,
    //     okText: '确认',
    //     cancelText: '取消',
    //     onOk: async () => {
    //       await pushAppointMutation({ beefId });
    //       refetch();
    //     },
    //   });
    // }
  /**
   * 打开处理流程表格
   * @param beefId 
   */
  const openProcessForm = (beefId: string) => {
    console.log("openProcessForm", beefId)
    
    setBeefIdProcess(beefId)
    setProcessOpen(true);
  }

  const columns = [
    {
      title: '类型',
      dataIndex: 'beefSource',
      render(beefSource: number) {
        if (beefSource === 1) {
          return "110警情"
        } else if (beefSource === 2) {
          return "矛盾纠纷自排查"
        }
      }
    },
    {
      title: '事件名称',
      dataIndex: 'beefName',
    },
    {
      title: '归属网络',
      dataIndex: 'belongNetwork',
    },
    {
      title: '详细地址',
      dataIndex: 'beefAddress',
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      render(riskLevel: string, obj: IBeef) {
        if (riskLevel === '0') {
          return <Button type={"link"} onClick={() => { openRiskDrawHandler(obj.beefId) }} >待评估</Button>
        } else if (riskLevel === '1') {
          return <Button type={"default"} onClick={() => { openRiskDrawHandler(obj.beefId) }}>一般类</Button>
        } else if (riskLevel === '2') {
          return <Button type={"primary"} onClick={() => { openRiskDrawHandler(obj.beefId) }}>关注类</Button>
        } else if (riskLevel === '3') {
          return <Button danger onClick={() => { openRiskDrawHandler(obj.beefId) }}>重点类</Button>
        }
      }
    },
    // {
    //   title: '纠纷类型',
    //   dataIndex: 'beefType',
    //   render(beefType: number) {
    //     const arr = dataSourceBeefType?.list.filter(e => e.beefTypeId === beefType);
    //     if (arr && arr.length > 0) {
    //       return arr[0].beefTypeName
    //     }
    //   }
    // },
    {
      title: '纠纷详情',
      dataIndex: 'beefDetail',
      width: "200px",
      render(beefDetail: string) {
        return <Tooltip title={beefDetail}>
          <span>{beefDetail && beefDetail.length > 30 ? beefDetail.substring(0, 38) + '...' : beefDetail}</span>
        </Tooltip>
      }
    },
    {
      title: '流程状态',
      dataIndex: 'status',
      render(status: number, project: IBeef) {
        return <Button type={'link'} onClick={() => {
          setBeefIdSlove(project.beefId)
          setOpenBeefSolveStep(true);
        }}> 查看</Button >
      }
    },
    {
      title: '更多操作',
      render(project: IBeef) {
        return (
          <Space>
            <Button
              onClick={() => {
                setUpdate(project);
                setIsedit(1);
                setOpen(true);
              }}
            >
              查看基本信息
            </Button>
            {
              getButton(project.status, project.beefId, project.beefFlowUserId, project.riskLevel)
            }
          </Space>
        );
      },
    },
  ]
  /**
   * 获取到对应的按钮
   */
  const getButton = (status: number, beefId: string, beefFlowUserId: string, riskLevel: string) => {
    const userType = sys.userInfo.sysRoleId;
    console.log('userType', beefFlowUserId)
    
    if (userType === 3) {
      return null;
    }
    // 民警登录
    if(userType == 2){
      return <Space>
        {
          (status === 1 || status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { openProcessForm(beefId) }}  > 处理  </Button> : null
        }
        {
          (status === 1 || status  == 2 || status == 4  ) ? <Button type={"primary"} onClick={() => { overBeefHandler(beefId) }}  > 确认处理完成  </Button> : null
        }
        {
          (status === 1 || status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { sendToZSZXHandler(beefId) }}  > 推送到综治中心  </Button> : null
        }
        {
          (status === 3 ) ? <Button type={"primary"} onClick={() => { signalBeefHandler(beefId) }}  > 签收任务  </Button> : null
        }
        {
          (status === 6 ) ? <Button type={"primary"} onClick={() => { backTORiskHandler(beefId) }}  > 退回重新调解  </Button> : null
        }
                {
          (status === 6 ) ? <Button type={"primary"} onClick={() => { callBackHandler(beefId) }}  > 电话回访  </Button> : null
        }
        {
          (status === 100 ) ? <Button type={"primary"}   > 已经推送到综治中心  </Button> : null
        }
      </Space>
    } else if(userType == 4){
      return <Space>
          {
            (status === 100 ) ? <Button type={"primary"} onClick={() => { signalBeefHandler(beefId) }}  > 签收任务  </Button> : null
          } 
          {
          (status === 1 || status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { openProcessForm(beefId) }}  > 处理  </Button> : null
          }
          {
          (status === 1 || status  == 2 || status == 4  ) ? <Button type={"primary"} onClick={() => { overBeefHandler(beefId) }}  > 确认处理完成  </Button> : null
          }
          {
          ( status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { setAssionOpen(true) ;setBeefIdAssign(beefId) }}  > 指派人员  </Button> : null
          }
           {
          (status === 6 ) ? <Button type={"primary"} onClick={() => { backTORiskHandler(beefId) }}  > 退回重新调解  </Button> : null
          }
          {
          (status === 6 ) ? <Button type={"primary"} onClick={() => { callBackHandler(beefId) }}  > 电话回访  </Button> : null
          }
      </Space>

    }else if(userType == 5){
      return <Space>
      {
        (status === 3 ) ? <Button type={"primary"} onClick={() => { signalBeefHandler(beefId) }}  > 签收任务  </Button> : null
      } 
      {
      (status === 1 || status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { openProcessForm(beefId) }}  > 处理  </Button> : null
      }
      {
      (status === 1 || status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { overBeefHandler(beefId) }}  > 确认处理完成  </Button> : null
      }
      {
      ( status  == 2 || status == 4) ? <Button type={"primary"} onClick={() => { sendToZSZXHandler(beefId) }}  > 推送到综治中心  </Button> : null
      }
       {
      (status === 6 ) ? <Button type={"primary"} onClick={() => { backTORiskHandler(beefId) }}  > 退回重新调解  </Button> : null
      }
      {
      (status === 6 ) ? <Button type={"primary"} onClick={() => { callBackHandler(beefId) }}  > 电话回访  </Button> : null
      }
  </Space>
    }
    //签收
    // if (status === 1 || status === 3 || status === 100) {
    //   return <Button type={"primary"} onClick={() => { signalBeefHandler(beefId) }}  > 签收 </Button>
    // }

    // //所长和综治中心指派人员
    // if ((userType === 3 || userType === 4) && beefFlowUserId == sys.userInfo.sysId) {

    //   return <Button type={"link"} onClick={() => {
    //     setBeefIdAssign(beefId)
    //     setAssionOpen(true)
    //   }}> 指派人员  </Button>
    // }

    //民警和综治中心处理
    // if ((userType === 2 || userType === 4) && beefFlowUserId == sys.userInfo.sysId || userType === 1) {
    //   return <Space>
    //     {
    //       (status !== 5 && status !== 6) ? <Button type={"primary"} onClick={() => { openProcessForm(beefId) }}  > 处理  </Button> : null
    //     }
    //     {
    //       (status !== 5 && status !== 6) ? <Button type={"primary"} onClick={() => {
    //         // sendToZSZXHandler(beefId)
    //         setBeefIdAssign(beefId)
    //         setAssionOpen(true)
    //       }}  > 推送到综治中心  </Button> : null
    //     }
    //     {
    //       (status !== 5 && status !== 6) ? <Button type={"primary"} onClick={() => { overBeefHandler(beefId) }}  > 确认处理完成  </Button> : null
    //     }
    //     {
    //       (status !== 5 && status !== 6 && status !== 1) ? <Button type={"primary"} onClick={() => { backTORiskHandler(beefId) }}  > 退回评估  </Button> : null
    //     }
    //     {
    //       (status === 5) ? <Button type={"primary"} onClick={() => { callBackHandler(beefId) }}  > 电话回访  </Button> : null
    //     }
    //     {
    //       riskLevel === "0" ? <Button type={"primary"} onClick={() => { openRiskDrawHandler(beefId) }} >评估</Button> : null
    //     }

    //   </Space>
    // }

  }
  return <WorkPlacePageContainer>
    <div className="work-header">
      <div className="work-header-content">
        <div className="work-header-content-left">
          <Avatar src={sys.userInfo.sysAvater} size={100} />
          <div className="work-header-content-left-content" style={{ marginLeft: '1rem', marginBottom: 0, fontWeight: 700, fontSize: '24px' }}>
            {sys.userInfo.sysName} 欢迎使用
          </div>
        </div>
        <div className="work-header-content-right">
          <div className="work-header-content-right-item" onClick={() => { navigate({ pathname: "/backweb/beef" }); setNavi({ ...navi, defaultSelectedKeys: ['13'] }) }}>
            <div className="work-header-content-right-item-title" style={{ cursor: 'pointer' }}>
              <SvgIcon name="address-card" size={20} color="#1677ff" />
              <h4 style={{ marginLeft: '1rem' }}>全部</h4>
            </div>
            <div className="num" style={{ color: '#1677ff' }}>{dataSource?.all}</div>
          </div>
          <div className="work-header-content-right-item">
            <div className="work-header-content-right-item-title">
              <SvgIcon name="list-check" size={20} color="#f10" />
              <h4 style={{ marginLeft: '1rem' }}>待处理矛排任务</h4>
            </div>
            <div className="num" style={{ color: '#f10' }}>{dataSource?.todo}</div>
          </div>
          <div className="work-header-content-right-item  add-Btn">
            <Card style={{ width: '150px', backgroundColor: '#1677ff' }} onClick={() => { setIsedit(0); setOpen(true) }}>
              <h1 style={{ textAlign: 'center', cursor: 'pointer', color: '#fff', fontFamily: 'Times New Roman' }}>
                添加
              </h1>
            </Card>
          </div>
        </div>
      </div>
    </div>
    <TableContainer >
      {isError ? (
        <ErrorBox error={error as { message: string }} />
      ) : (
        <Table rowSelection={{ type: 'checkbox' }} dataSource={dataSource?.todoBeefs} columns={columns} loading={isLoading} rowKey={(row) => row?.beefId} />
      )}
    </TableContainer>
    <BeefForm open={open} onRef={FormRef}  openFn={openFn} setUpdate={setUpdate} beef={update} isEdit={isEdit} refetch={refetch as any} />
    {/* <BeefRisk open={openRisk} setOpen={closeBeefRiskFn} beefId={beefId} /> */}
    <BeefSloveStepForm open={openBeefSolveStep} setOpen={closeBeefSolveStepHandler} beefId={beefIdSlove} />
    <AssignForm open={assignOpen} openFn={closeAssignHandler} beefId={beefIdAssign} refetch={refetch} />
    <ProcessForm open={processOpen} openFn={closeProcessHandler} beefId={beefIdProcess} refetch={refetch} />

  </WorkPlacePageContainer>;
};

export default WorkPlacePage;


const WorkPlacePageContainer = styled.div`
  .work-header {
    border-bottom :1px solid #e8eaec;
    padding: 16px 32px 0 32px;
    background-color:#fff;
    .work-header-content{
      display: flex;
      height: 150px;
      .work-header-content-left{
        padding-left: 1.5rem;
        display: flex;
        flex: 2;
        align-items: center;
      }
      .work-header-content-right{
        flex: 1;
        display: flex;
        .work-header-content-right-item {
          flex: 1;
          .work-header-content-right-item-title {
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }
    .add-Btn {

    }
    .num {
      font-size:60px;
      font-family: 'Times New Roman';
      text-align: center;
    }
  }

`